import { OPERATOR,CRITERIA_TYPE } from '@/store/mutation-types'
import { isArray } from 'lodash'
export default class Criteria {
    #stack = new Stack()
    constructor() {
      this.param = {
        criterions: [],
        orders: []
      }
    }
    addCriterion(key, operator, value) {
      const obj = {
        fieldName: key,
        operator: operator,
        value: value
      }
      if (this.#stack.length() === 0) {
        this.param.criterions.push(obj)
      } else {
        this.#stack.peek().criterions.push(obj)
      }
      return this
    }
    addOrder({fieldName, desc}) {
      this.param.orders.push({
        fieldName: fieldName,
        desc: desc || false
      })
      return this
    }
    or() {
      this.#stack.push({ type: CRITERIA_TYPE.OR, criterions: [] })
      return this
    }
    and() {
      this.#stack.push({ type: CRITERIA_TYPE.AND, criterions: [] })
      return this
    }
    end() {
      const stack = this.#stack.pop()
      if (this.#stack.length() === 0) {
        this.param.criterions.push(stack)
      } else {
        this.#stack.peek().criterions.push(stack)
      }
      return this
    }
    concatCriterions(list){
      this.param.criterions = this.param.criterions.concat(list)
    }
    addCriterions(param, operator = OPERATOR.EQ) { // 生成单层简单查询条件
      Object.keys(param).forEach(key => {
        if(key.includes('@')){//处理查询类型不一致的情况 使用示例'key@EQ'
          let i = key.indexOf('@')
          this.param.criterions.push({
            fieldName: key.slice(0,i),
            operator: key.slice(i+1,key.length),
            value: param[key]
          })
        }else if(isArray(param[key])){//处理范围查询情况，使用示例[1,10]或['2022-01-01','2022-12-31']
          if(param[key][0]){
            this.param.criterions.push({
              fieldName: key,
              operator: OPERATOR.GE,
              value:param[key][0]
            })
          }
          if(param[key][1]){
            this.param.criterions.push({
              fieldName: key,
              operator: OPERATOR.LE,
              value:param[key][1]
            })
          }
        }else{
          this.param.criterions.push({
            fieldName: key,
            operator: operator,
            value:param[key]
          })
        }
      })
      return this
    }
    addOrders(order) {
      Object.keys(order).forEach(key => {
        this.param.orders.push({
          fieldName: key,
          desc: order[key]
        })
      })
      return this
    }
    getEncode() {
      return encodeURIComponent(JSON.stringify(this.param))
    }
}

export class Stack {
  constructor() {
    this.top = 0// 栈顶位置，初始化为0
    this.dataStore = []// 保存栈内元素，初始化为一个空数组
  }
  push(element) { // 入栈
    this.dataStore[this.top++] = element
  }
  pop() { // 出栈
    return this.dataStore[--this.top]
  }
  peek() { // 查看栈顶元素
    return this.dataStore[this.top - 1]
  }
  clear() { // 清空栈
    this.top = 0
  }
  length() { // 栈内存放元素的个数
    return this.top
  }
}
